package emt.friendtracking;

import java.util.Iterator;
import java.util.List;

import com.google.android.maps.*;

import emt.friendtracking.contact.EmtContactsActivity;
import emt.friendtracking.maps.TrackingActivity;
import emt.friendtracking.smsmodule.SendSMS;
import emt.friendtracking.smsmodule.SmsReceiverService;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

//The Log messages have a "TODO"-comment followed with the message that is logged by the Log method.

public abstract class BaseActivity extends MapActivity
{ 
	protected static boolean isSmsReceiverServiceRunning = false;

	public static SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MyApplication.getAppContext());

	private static long idOfNewRow = -1;
	
	public volatile static SendSMS sms = new SendSMS();

	private static final String TAG = BaseActivity.class.getSimpleName(); 

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);

		Log.d(TAG, "onCreated."); //TODO "onCreated."
	}
	/* *************** Menu handling *************** */

	/**
	 *  Called only once first time menu is clicked on
	 */
	@Override 
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		getMenuInflater().inflate(R.menu.menu, menu);
		Log.d(TAG, "Menu has been opened."); //TODO "Menu has been opened."
		return true;
	}

	/**
	 *  Called every time user clicks on a menu item
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		Log.d(TAG, "Selecting in the menu."); //TODO "Selecting in the menu."
		switch (item.getItemId()) 
		{
			case R.id.itemPrefs:
				startActivity(new Intent(this, PrefsActivity.class)
				.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
				Log.d(TAG, "ItemPrefs has been selected."); //TODO "ItemPrefs has been selected."
				break;

			case R.id.itemToggleSmsReceiverService:
				if (isSmsReceiverServiceRunning) 
				{
					stopService(new Intent(this, SmsReceiverService.class));
					isSmsReceiverServiceRunning = false;
					Log.d(TAG, "SmsReceiverService is stopped."); //TODO "SmsReceiverService is stopped."
				} 
				else 
				{
					startService(new Intent(this, SmsReceiverService.class));
					isSmsReceiverServiceRunning = true;
					Log.d(TAG, "SmsReceiverService is started."); //TODO "SmsReceiverService is started."
				}
				isServiceRunning(SmsReceiverService.class.getName());
				break;

			case R.id.itemSmsSend:
				startActivity(new Intent(this, EmtContactsActivity.class)
				.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
				Log.d(TAG, "ItemSmsSend has been selected."); //TODO "ItemSmsSend has been selected."
				break;

			case R.id.itemTracking:
				startActivity(new Intent(this, TrackingActivity.class)
				.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
				Log.d(TAG, "ItemTracking has been selected."); //TODO "ItemTracking has been selected."
				break;
				
			case R.id.itemHistory:
				startActivity(new Intent(this, MainActivity.class)
				.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
				Log.d(TAG, "ItemHistory has been selected."); //TODO "ItemHistory has been selected."
				break;
		}
		return true;
	}

	/**
	 *  Called every time menu is opened
	 */
	@Override
	public boolean onMenuOpened(int featureId, Menu menu) 
	{ 
		MenuItem toggleItem = menu.findItem(R.id.itemToggleSmsReceiverService); 
		if (isSmsReceiverServiceRunning) 
		{ 
			toggleItem.setTitle(R.string.titleServiceStop);
			toggleItem.setIcon(android.R.drawable.ic_media_pause);
		} 
		else 
		{ 
			toggleItem.setTitle(R.string.titleServiceStart);
			toggleItem.setIcon(android.R.drawable.ic_media_play);
		}
		return true;
	}
	
	public static String getUsername()
	{
		TelephonyManager tMgr = (TelephonyManager)MyApplication.getAppContext().getSystemService(Context.TELEPHONY_SERVICE);
		Log.i(TAG, "number " + tMgr.getLine1Number() + " ---");
		return prefs.getString("username", tMgr.getLine1Number()==null?"Unknown":tMgr.getLine1Number().length()==0?"Unknown":tMgr.getLine1Number());//This returns the owners telephone number
	}

	public static float getAccuracy()
	{
		return Float.parseFloat(prefs.getString("accuracy", "100"));
	}

	public static boolean ServiceActivated(IService service)
	{
		if(service.isActive())
		{
			isSmsReceiverServiceRunning = true;
		}
		return isSmsReceiverServiceRunning;
	}

	public static long getIdOfNewRow()
	{
		return idOfNewRow;
	}

	public static void setIdOfNewRow(long id)
	{
		Log.d(TAG, "New Id recieved: " + id);
		idOfNewRow = id;
		Log.d(TAG, "New Id stored: " + BaseActivity.idOfNewRow);
	}
	
	private boolean isServiceRunning(String serviceName)
	{
        boolean serviceRunning = false;
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> l = am.getRunningServices(10000);
        Iterator<ActivityManager.RunningServiceInfo> i = l.iterator();
        while (i.hasNext()) 
        {
            ActivityManager.RunningServiceInfo runningServiceInfo = (ActivityManager.RunningServiceInfo) i
                    .next();
            Log.i(TAG, "services: " + runningServiceInfo.service.getClassName());
            if(runningServiceInfo.service.getClassName().equals(serviceName))
            {
                serviceRunning = true;
            }
        }
        return serviceRunning;
    }
}
